package com.ttx.pattern.example.chain.tomcat.pipeline;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;

/**
 *
 * 参考org.apache.catalina.core.StandardPipeline
 *
 * @author TimFruit
 * @date 19-5-12 下午11:04
 */
public class StandardPipeline implements Pipeline {

    private Valve first;



    @Override
    public void addValve(Valve valve) {
        if(first==null){
            first=valve;
        }else {
            Valve p=first;
            while(p.getNext()!=null){
                p=p.getNext();
            }
            p.setNext(valve);
        }
    }

    @Override
    public void removeValve(Valve valve) {
        if(first==null){
            return;
        }
        if(first==valve){
            Valve p=first;
            first=first.getNext();
            p.setNext(null);
            return;
        }
        Valve p=first;
        Valve t=null;
        while (p.getNext()!=null){
            t=p.getNext();
            if(t!=valve){
                p=t;
            }else {
                p.setNext(t.getNext());
                t.setNext(null);
                break;
            }
        }
    }

    @Override
    public Valve getFirst() {
        return first;
    }



    // 在这里调用链中"阀门"方法
    protected synchronized void startInternal()  {

        // Start the Valves in our pipeline (including the basic), if any
        Valve current = first;

        while (current != null) {
            if (current instanceof Lifecycle)
                ((Lifecycle) current).start();
            current = current.getNext();
        }

    }
}
